from flask import Flask, request, jsonify, render_template_string
from led_data import get_led_database
import math

app = Flask(__name__)

def calculate_optimal_design(input_current, target_lumens):
    """计算最优LED设计方案"""
    led_db = get_led_database()
    best_design = None
    min_cost = float('inf')
    
    for led in led_db:
        # 计算需要的LED数量
        min_leds = math.ceil(target_lumens / led['luminous_flux'])
        
        # 尝试不同的串并联组合
        for series_count in range(1, min_leds + 1):
            parallel_count = math.ceil(min_leds / series_count)
            total_leds = series_count * parallel_count
            
            # 计算总电压和电流
            total_voltage = series_count * led['voltage']
            total_current = parallel_count * led['current']
            
            # 计算限流电阻
            if input_current > 0:
                supply_voltage = 12  # 假设12V电源
                resistor_voltage = supply_voltage - total_voltage
                if resistor_voltage > 0:
                    resistor_value = resistor_voltage / (total_current * 1000)  # 转换为kΩ
                    resistor_power = resistor_voltage * total_current
                else:
                    resistor_value = 0
                    resistor_power = 0
            else:
                resistor_value = 0
                resistor_power = 0
            
            # 计算总成本
            led_cost = total_leds * led['cost']
            resistor_cost = 0.05 if resistor_value > 0 else 0  # 电阻成本
            total_cost = led_cost + resistor_cost
            
            # 计算实际亮度和效率
            actual_lumens = total_leds * led['luminous_flux']
            total_power = total_voltage * total_current + resistor_power
            efficiency = actual_lumens / total_power if total_power > 0 else 0
            
            # 检查是否满足要求
            if actual_lumens >= target_lumens:
                design = {
                    'led_model': led['model'],
                    'led_count': total_leds,
                    'series_count': series_count,
                    'parallel_count': parallel_count,
                    'total_voltage': round(total_voltage, 2),
                    'total_current': round(total_current, 3),
                    'resistor_value': round(resistor_value, 2),
                    'resistor_power': round(resistor_power, 2),
                    'total_cost': round(total_cost, 2),
                    'actual_lumens': round(actual_lumens, 1),
                    'efficiency': round(efficiency, 1),
                    'power_consumption': round(total_power, 2)
                }
                
                if total_cost < min_cost:
                    min_cost = total_cost
                    best_design = design
    
    return best_design

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/calculate', methods=['POST'])
def calculate():
    data = request.json
    input_current = float(data.get('current', 0))
    target_lumens = float(data.get('lumens', 0))
    
    if input_current <= 0 or target_lumens <= 0:
        return jsonify({'error': '请输入有效的电流和亮度值'}), 400
    
    design = calculate_optimal_design(input_current, target_lumens)
    
    if design:
        return jsonify(design)
    else:
        return jsonify({'error': '无法找到满足要求的设计方案'}), 400

HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车灯智能成本优化设计器</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .main-container {
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
        }
        .card {
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border-radius: 15px;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 20px;
        }
        .btn-calculate {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 12px 30px;
            font-size: 16px;
            border-radius: 25px;
            transition: all 0.3s ease;
        }
        .btn-calculate:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .result-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .result-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .result-item:last-child {
            border-bottom: none;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="card">
            <div class="card-header">
                <h2 class="mb-0"><i class="fas fa-lightbulb"></i> 车灯智能成本优化设计器</h2>
                <p class="mb-0 opacity-75">输入电流和亮度需求，获取最优LED设计方案</p>
            </div>
            <div class="card-body p-4">
                <form id="designForm">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="current" class="form-label">输入电流 (A)</label>
                            <input type="number" class="form-control" id="current" 
                                   placeholder="例如: 0.35" step="0.01" min="0.01" required>
                        </div>
                        <div class="col-md-6">
                            <label for="lumens" class="form-label">目标亮度 (lm)</label>
                            <input type="number" class="form-control" id="lumens" 
                                   placeholder="例如: 800" step="1" min="1" required>
                        </div>
                    </div>
                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-calculate">
                            <i class="fas fa-calculator"></i> 计算最优方案
                        </button>
                    </div>
                </form>
                
                <div class="loading" id="loading">
                    <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
                    <p class="mt-2">正在计算最优方案...</p>
                </div>
                
                <div id="result" style="display: none;">
                    <div class="result-card">
                        <h4 class="text-primary mb-3"><i class="fas fa-chart-line"></i> 最优设计方案</h4>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="result-item">
                                    <span>LED型号:</span>
                                    <strong id="ledModel">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>LED数量:</span>
                                    <strong id="ledCount">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>连接方式:</span>
                                    <strong id="connection">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>工作电压:</span>
                                    <strong id="voltage">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>工作电流:</span>
                                    <strong id="currentResult">-</strong>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="result-item">
                                    <span>限流电阻:</span>
                                    <strong id="resistor">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>实际亮度:</span>
                                    <strong id="actualLumens">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>光效效率:</span>
                                    <strong id="efficiency">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>功率损耗:</span>
                                    <strong id="power">-</strong>
                                </div>
                                <div class="result-item">
                                    <span>总成本:</span>
                                    <strong class="text-success" id="cost">-</strong>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('designForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const current = document.getElementById('current').value;
            const lumens = document.getElementById('lumens').value;
            
            if (!current || !lumens) {
                alert('请填写所有必填字段');
                return;
            }
            
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';
            
            try {
                const response = await fetch('/calculate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        current: parseFloat(current),
                        lumens: parseFloat(lumens)
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    displayResult(data);
                } else {
                    alert(data.error || '计算失败，请重试');
                }
            } catch (error) {
                alert('网络错误，请重试');
                console.error('Error:', error);
            } finally {
                document.getElementById('loading').style.display = 'none';
            }
        });
        
        function displayResult(data) {
            document.getElementById('ledModel').textContent = data.led_model;
            document.getElementById('ledCount').textContent = data.led_count + ' 颗';
            document.getElementById('connection').textContent = 
                data.series_count + ' 串 ' + data.parallel_count + ' 并';
            document.getElementById('voltage').textContent = data.total_voltage + ' V';
            document.getElementById('currentResult').textContent = data.total_current + ' A';
            document.getElementById('resistor').textContent = 
                data.resistor_value > 0 ? data.resistor_value + ' Ω' : '无需';
            document.getElementById('actualLumens').textContent = data.actual_lumens + ' lm';
            document.getElementById('efficiency').textContent = data.efficiency + ' lm/W';
            document.getElementById('power').textContent = data.power_consumption + ' W';
            document.getElementById('cost').textContent = '¥' + data.total_cost;
            
            document.getElementById('result').style.display = 'block';
        }
    </script>
</body>
</html>
'''

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
